package com.iexbuy.ihg.ui.activity;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Notification;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;

import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.AppVersion;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.fragment.HomeFragment;
import com.iexbuy.ihg.ui.fragment.HomeHuiguoFragment;
import com.iexbuy.ihg.ui.fragment.HomeMianDanFragment;
import com.iexbuy.ihg.ui.fragment.HomeYunGuoFragment;
import com.iexbuy.ihg.ui.fragment.HomeWedeFragment;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.utils.UnitUtils;
import com.iexbuy.ihg.utils.Utils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.slidingmenu.lib.SlidingMenu;


public class MainTabActivity extends TabActivity implements OnCheckedChangeListener, OnClickListener{
	
	private Intent intent;
	private TabHost tabHost;
	private RadioGroup radioGroup;
	
	private static final String TAB1 = "TAB1";
	private static final String TAB2 = "TAB2";
	private static final String TAB3 = "TAB3";
	private static final String TAB4 = "TAB4";
	private static final String TAB5 = "TAB5";

	private final int[] buttonIdArray = {R.id.radio_button1, R.id.radio_button2, R.id.radio_button3, R.id.radio_button4, R.id.radio_button5};
	
	private static MainTabActivity instance;
	
//	private SlidingPaneLayout mSlidingMenu;
	private SlidingMenu mSlidingMenu;

	private static boolean showingPushMessage = false;
	
	private boolean isMiddleNavChangeing = false;
	private List<MiddleNavBtnClickLisener> middleNavBtnClickLisenerList = new ArrayList<MiddleNavBtnClickLisener>();
	
	private boolean isCheckUpdte = false;
	
	public static MainTabActivity getInstance() {
		return instance;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_tab);
		initTab();
//		checkApkUpdate();
		updateAnylizeConfig();
		instance = this;
//		if (App.sPreferences.getAutoLogin()) {
//			startLoginTask(App.sPreferences.getUser(),App.sPreferences.getPsw());
//		}
		
		initMsgPush();
	}
	
	
	private void initTab(){
		// 获取当前Activity的tabhost
		tabHost = getTabHost();
		tabHost.setup();

		// 设置TAB
		intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
		intent.putExtra("TAG", 0);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, HomeFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, false);
		tabHost.addTab(tabHost.newTabSpec(TAB1).setIndicator(TAB1)
				.setContent(intent));
		
		intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
		intent.putExtra("TAG", 1);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, HomeHuiguoFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, false);
		tabHost.addTab(tabHost.newTabSpec(TAB2).setIndicator(TAB2)
				.setContent(intent));
		
		intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
		intent.putExtra("TAG", 2);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, HomeYunGuoFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, false);
		tabHost.addTab(tabHost.newTabSpec(TAB3).setIndicator(TAB3)
				.setContent(intent));
		
		intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
		intent.putExtra("TAG", 3);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, HomeMianDanFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, false);
		tabHost.addTab(tabHost.newTabSpec(TAB4).setIndicator(TAB4)
				.setContent(intent));

		intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
		intent.putExtra("TAG", 4);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, HomeWedeFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, false);
		tabHost.addTab(tabHost.newTabSpec(TAB5).setIndicator(TAB4)
				.setContent(intent));
		
		//设置图标边距
		int iconSize = UnitUtils.dip2px(getApplicationContext(), 25);
		RadioButton radio_button1 = (RadioButton) findViewById(R.id.radio_button1);
        Drawable drawable1 = getResources().getDrawable(R.drawable.icon_tab_nav_buy);
        drawable1.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        radio_button1.setCompoundDrawables(null, drawable1, null, null);//只放左边

		RadioButton radio_button2 = (RadioButton) findViewById(R.id.radio_button2);
		Drawable drawable2 = getResources().getDrawable(R.drawable.icon_tab_nav_traded);
		drawable2.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		radio_button2.setCompoundDrawables(null, drawable2, null, null);//只放左边

		RadioButton radio_button3 = (RadioButton) findViewById(R.id.radio_button3);
		Drawable drawable3 = getResources().getDrawable(R.drawable.icon_tab_nav_raffle);
		drawable3.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		radio_button3.setCompoundDrawables(null, drawable3, null, null);//只放左边
        
        RadioButton radio_button4 = (RadioButton) findViewById(R.id.radio_button4);
        Drawable drawable4 = getResources().getDrawable(R.drawable.icon_tab_nav_money);
        drawable4.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        radio_button4.setCompoundDrawables(null, drawable4, null, null);//只放左边

		RadioButton radio_button5 = (RadioButton) findViewById(R.id.radio_button5);
		Drawable drawable5 = getResources().getDrawable(R.drawable.icon_tab_nav_my);
		drawable5.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		radio_button5.setCompoundDrawables(null, drawable5, null, null);//只放左边
        
        radioGroup = (RadioGroup) findViewById(R.id.main_tab);
		radioGroup.setOnCheckedChangeListener(this);
		// 设置默认显示的tab
		((RadioButton) findViewById(R.id.radio_button1)).setChecked(true);
		tabHost.setCurrentTabByTag(TAB1);
	}
	
	public OnClickListener mOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			default:
				break;
			}
		}
	};
	
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.radio_button1:
			tabHost.setCurrentTabByTag(TAB1);
			break;
		case R.id.radio_button2:
			tabHost.setCurrentTabByTag(TAB2);
			break;
		case R.id.radio_button3:
			tabHost.setCurrentTabByTag(TAB3);
			break;
		case R.id.radio_button4:
			tabHost.setCurrentTabByTag(TAB4);
			break;
		case R.id.radio_button5:
			tabHost.setCurrentTabByTag(TAB5);
			break;
		default:
			break;
		}
	}
	
	public void setCurrentTab(int index) {
		((RadioButton) findViewById(buttonIdArray[index])).setChecked(true);
		tabHost.setCurrentTab(index);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	
	private void initMsgPush() {
		// Push: 以apikey的方式登录，一般放在主Activity的onCreate中。
        // 这里把apikey存放于manifest文件中，只是一种存放方式，
        // 您可以用自定义常量等其它方式实现，来替换参数中的Utils.getMetaValue(PushDemoActivity.this,
        // "api_key")
        PushManager.startWork(instance.getApplicationContext(),
                PushConstants.LOGIN_TYPE_API_KEY,
                Utils.getMetaValue(instance, "api_key"));
        // Push: 如果想基于地理位置推送，可以打开支持地理位置的推送的开关
        // PushManager.enableLbs(getApplicationContext());

        // Push: 设置自定义的通知样式，具体API介绍见用户手册，如果想使用系统默认的可以不加这段代码
        // 请在通知推送界面中，高级设置->通知栏样式->自定义样式，选中并且填写值：1，
        // 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应
        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
        		getApplicationContext(), R.layout.notification_custom_builder,
                R.id.notification_icon,
                R.id.notification_title,
                R.id.notification_text);
        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
        cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        cBuilder.setStatusbarIcon(getApplicationInfo().icon);
        cBuilder.setLayoutDrawable(R.drawable.simple_notification_icon);
        PushManager.setNotificationBuilder(instance, 1, cBuilder);
        
	}
	

	public void toggleSlidingMenu() {
		if (!isMenuOpen()) {
			openSlidingMenu();
		} else {
			closeSlidingMenu();
		}
	}
	
	public void enableSlidingMenuTouch(boolean isOpen) {
		if (!isOpen) {
			mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		} else {
			mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}

	public boolean isMenuOpen() {
		return mSlidingMenu.isMenuShowing();
	}

	public void closeSlidingMenu() {
		mSlidingMenu.showContent(true);//显示内容;
	}

	public void openSlidingMenu() {
		mSlidingMenu.showMenu(true);//显示菜单
	}
	
	/**
	 * 检查应用更新
	 */
	private void checkApkUpdate() {
		if (!isCheckUpdte) {
			HashMap<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("appId", "EduBossTeach");
			ServiceHelper.send(this, ServiceHelper.GET_APK_LAST_VERSION, paramMap, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					isCheckUpdte = true;
					String responseString = responseInfo.result;
					AppVersion response = JsonUtils.parseJsonStrToObject(responseString, AppVersion.class);
					if (response.getVersion().compareTo(App.sAPKVersionName) > 0) {
						CommUtil.showUpdateApkDialog(response, MainTabActivity.this);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {
				}
			});
		}
	}
	
	public void hideBadgeSetting() {
//		if (badgeSetting != null && badgeSetting.isShown()) {
//			TranslateAnimation anim = new TranslateAnimation(-100, 0, 0, 0);
//	        anim.setInterpolator(new BounceInterpolator());
//	        anim.setDuration(1000);
//	        badgeSetting.hide();
//		}
	}
	
	@Override
    protected void onNewIntent(Intent intent) {
		showingPushMessage = intent.getBooleanExtra("showingPushMessage", false);
		Log.i(getClass().getSimpleName(), "onNewIntent(), showingPushMessage="+showingPushMessage);
		//如果是从消息推送通知点进来的，自动打开消息详情页面
        new ShowMessageTask().execute();
	}
	
	class ShowMessageTask extends AsyncTask<Void, Void, Long> {
		@Override
		protected Long doInBackground(Void... param) {
			showMessage();
			return null;
		}
	}
	
	public void showMessage() {
		Log.i(getClass().getSimpleName(), "showMessage(), showingPushMessage="+showingPushMessage);
		if (showingPushMessage) {
			Intent intent = new Intent(MainTabActivity.this, SingleFragmentActivity.class);
//			intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, MemberMessageDetailFragment.class);
			intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true);
			MainTabActivity.this.startActivity(intent);
			showingPushMessage = false;
		}
	}
	
	/**
	 * @param showingPushMessage the showingPushMessage to set
	 */
	public static void setShowingPushMessage(boolean showingPushMessage) {
		MainTabActivity.showingPushMessage = showingPushMessage;
	}
	
	private void updateAnylizeConfig() {
//		MobclickAgent.updateOnlineConfig(instance);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.radio_button2:
			//如果已选中中间的tag，传递给一个返回的事件
			if (isMiddleNavChangeing) {
				isMiddleNavChangeing = false;
			} else {
				Log.i("", "isMiddleNavChangeing "+isMiddleNavChangeing);
				for (MiddleNavBtnClickLisener listener : this.middleNavBtnClickLisenerList) {
					listener.onMiddleNavBtnDbClick();
				}
			}
			break;
		case R.id.radio_button3:
			hideBadgeSetting();
			break;
		default:
			break;
		}
		
	}
	public void addMiddleNavBtnClickLisener(MiddleNavBtnClickLisener listener) {
		if (listener != null) {
			this.middleNavBtnClickLisenerList.clear();
			this.middleNavBtnClickLisenerList.add(listener);
		}
	}
	
	public interface MiddleNavBtnClickLisener {
		public void onMiddleNavBtnDbClick();
	}
}